<template>
    <view class="mapBox">
        <view class="topBox">
            <view>
                部门电话
            </view>
            <image src="../static/telephone.png"></image>
        </view>
        <map id="map" ref="map" :longitude="center.longitude" :latitude="center.latitude" scale="16" :show-location="true" :enable-building="true"
            :enable-3D="true" :enable-poi="false" :markers="markers" @markertap="markertap"  @labeltap="markertap" @regionchange="regionchange" :max-scale="20" 
            :min-scale="12">
            <!-- 自定义气泡框样式  :markers="markers"-->
            <!-- <cover-view slot="callout">
                    <block v-for="item in markers" :key="item.id">
                            <cover-view :marker-id="item.id" class="marker-point">
                                    <cover-image class="marker-img" :src='item.iconPath'
        style="width:35px;"></cover-image>
                                    <cover-view class="marker-name">{{ item.title }}</cover-view>
                                  </cover-view>
                          </block>
                  </cover-view> -->
        </map>
    </view>
</template>

<script>
// import color from 'uview-ui/libs/function/color.js';
// import datas from './data.js'
// import {
//     IsPtInPoly
// } from './libs/IsPtInPoly.js'
export default {
    data() {
        return {
            center: {
                latitude: 39.645243,
                longitude: 111.444696
            },
            markers: [],
            cates: [{
                name: '景点',
                cateId: 0,
                iconPath: '../../static/icon.png',
            }],
            cateId: 0,
            cateIcon: '../../static/icon.png',
            showDetail: false,
            markerInfo: {},
            baseUrl: this.$baseUrl,
            innerAudioContext: null,
            playStatus: false
        }
    },
    onLoad() {
        this.mapContext = uni.createMapContext("map");
    },
    onShow() {
        this.cates = [{
            name: '景点',
            cateId: 0
        }]
        // this.loadRegion()
        // this.initData()
        // this.setMarkersAndCluster()
    },
    methods: {
        getMarkerItemTitle(id) {
            return this.markers.filter(item =>
                item.id == id
            )
        },
        initData() {
            this.$asynApi.getTourCates().then(res => {
                // console.log(res)
                if (res.code == 200) {
                    let data = res.data
                    data.forEach(item => {
                        this.cates.push({
                            name: item.typeName,
                            cateId: item.id,
                            iconPath: this.$baseUrl + item.img
                        })
                    })
                }
            })
        },
        getList() {
            if (this.cateId == 0) {
                this.$asynApi.getSpotList({
                    scenicId: 1
                }).then(res => {
                    // console.log(res)
                    if (res.code == 200) {
                        let data = res.data || []
                        let markers = []
                        let points = []
                        data.forEach(item => {
                            let length = item.spotName.length
                            markers.push({
                                id: item.id,
                                latitude: item.latitude,
                                longitude: item.longitude,
                                title: item.spotName,
                                iconPath: '../../static/icon.png',
                                // width: 50,
                                // height: 58,
                                width: 35,
                                height: 40,
                                joinCluster: true,
                                label: {
                                    content: item.spotName,
                                    color: '#333',
                                    borderColor: "transparent",
                                    padding: 2,
                                    fontSize: 14,
                                    bgColor: '#fff',
                                    borderWidth: 2,
                                    color: '#333',
                                    borderRadius: 5,
                                    textAlign: 'right',
                                    display: 'ALWAYS',
                                    anchorX: 10,
                                    anchorY: -35
                                }
                                //     customCallout: {
                                //         display: 'ALWAYS',
                                // textAlign: 'right',
                                // anchorX: 10,
                                // anchorY: 30
                                //     },

                                // callout: {
                                // 	content: item.spotName,
                                // 	bgColor: '#ffffff',
                                // 	color: '#333',
                                // 	padding: 5,
                                // 	textAlign: 'center',
                                // 	fontSize: 14,
                                // 	borderRadius: 50,
                                // 	display: 'ALWAYS',
                                // 	anchorY: 96
                                // }
                            })
                            points.push({
                                latitude: item.latitude,
                                longitude: item.longitude
                            })
                        })
                        this.markers = markers
                    }
                })
            } else {
                this.$asynApi.getTourList({
                    typeId: this.cateId
                }).then(res => {
                    // console.log(res)
                    if (res.code == 200) {
                        let data = res.data || []
                        let markers = []
                        let points = []
                        data.forEach(item => {
                            let length = item.name.length
                            markers.push({
                                id: item.id,
                                latitude: item.latitude,
                                longitude: item.longitude,
                                title: item.name,
                                description: item.description,
                                imgList: item.img ? item.img.split(',') : [],
                                iconPath: this.cateIcon,
                                width: 35,
                                height: 40,
                                joinCluster: true,
                                label: {
                                    content: item.name,
                                    color: '#333',
                                    borderColor: "transparent",
                                    padding: 2,
                                    fontSize: 14,
                                    bgColor: '#fff',
                                    borderWidth: 2,
                                    color: '#333',
                                    borderRadius: 5,
                                    textAlign: 'right',
                                    display: 'ALWAYS',
                                    anchorX: 10,
                                    anchorY: -35
                                }
                                //     customCallout: {
                                //         display: 'ALWAYS',
                                // textAlign: 'right',
                                // anchorX: 10,
                                // anchorY: 30

                                //     },
                                // width: 50,
                                // height: 58,
                                // callout: {
                                // 	content: item.name,
                                // 	bgColor: '#ffffff',
                                // 	color: '#333',
                                // 	padding: 5,
                                // 	textAlign: 'center',
                                // 	fontSize: 14,
                                // 	borderRadius: 50,
                                // 	display: 'ALWAYS',
                                // 	anchorY: 96
                                // }
                            })
                            points.push({
                                latitude: item.latitude,
                                longitude: item.longitude
                            })
                        })
                        this.markers = markers
                    }
                })
            }
        },
        // 设置点聚合
        setMarkersAndCluster() {
            let that=this
            this.mapContext.initMarkerCluster({ // 初始化点聚合的配置
                enableDefaultStyle: false, // 是否使用默认样式
                zoomOnClick: true,
                gridSize: 60,
                complete(res) {
                    console.log('initMarkerCluster', res)
                    that.getList()
                }
            });
            this.mapContext.on("markerClusterCreate", (e) => {
                let clusterMarkers = []
                console.log(e);
                const clusters = e.clusters // 新产生的聚合簇
                clusters.forEach((cluster, index) => {
                    const {
                        center, // 聚合点的经纬度数组
                        clusterId, // 聚合簇id
                        markerIds // 已经聚合了的标记点id数组
                    } = cluster
                    let units = ["处", "间", "家", "处", "个", "个", "处", "个", "个", "个"]
                    console.log(this.getMarkerItemTitle(markerIds[0])[0].title);
                    let title = this.getMarkerItemTitle(markerIds[0])[0].title + '...等' + markerIds.length + units[this.cateId] + this.cates.filter(item => item.cateId == this.cateId)[0].name
                    let clusterObj = {
                        clusterId, //必须
                        ...center,
                        width: 35,
                        height: 40,
                        iconPath: this.cateIcon,
                        // iconPath: '../../static/circleBg.png',
                        // title: markerIds.length + '',
                        label: {// 定制聚合簇样式
                            content: title,
                            // content: markerIds.length + '',
                            fontSize: 14,
                            color: '#333',
                            // height: 30,
                            borderColor: "transparent",
                            padding: 2,
                            bgColor: '#fff',
                            borderWidth: 2,
                            color: '#333',
                            borderRadius: 5,
                            textAlign: 'right',
                            anchorX: 10,
                            anchorY: -35
                        }
                    }
                    clusterMarkers.push(clusterObj)
                })
                // 添加聚合簇
                this.mapContext.addMarkers({
                    markers: clusterMarkers,
                    clear: false, //是否先清空地图上所有的marker
                })
            });
            // this.mapContext.addMarkers({
            //     markers: this.markers,
            //     clear: true, // 是否先清空地图上所有marker
            // })
        },
        changeCate(data) {
            this.cateId = data.cateId
            this.cateIcon = data.iconPath ? data.iconPath : "../../static/icon.png"
            this.markers = []
            this.markerInfo = {}
            this.showDetail = false
            this.getList()
        },
        loadRegion() {
            let northeast = {
                latitude: 39.638832,
                longitude: 111.514382
            }
            let southwest = {
                latitude: 39.627682,
                longitude: 111.498879
            }

            for (var i = 9; i >= 0; i--) {
                for (var j = 9; j >= 0; j--) {
                    let layerParma1 = {
                        id: Number(i * 10 + j + 1),
                        src: 'https://k8s-bj.oss-accelerate.aliyuncs.com/laoniuwan/userfiles/images/guide_20240929/' + Number(i * 10 + j + 1) + '.png',
                        zIndex: 99999999999,
                        bounds: {
                            northeast: {
                                latitude: Number(northeast.latitude + (10 - i) * 0.01115),
                                longitude: Number(northeast.longitude - (10 - j) * 0.0155)
                            },
                            southwest: {
                                latitude: Number(southwest.latitude + (10 - i) * 0.01115),
                                longitude: Number(southwest.longitude - (10 - j) * 0.0155)
                            }
                        },
                        success: res => {
                            // console.log('成功', res)
                        },
                        fail: err => {
                            // console.log("失败：", err)
                        },
                        complete: (res) => {
                            // console.log(res)
                        }
                    }
                    this.mapContext.addGroundOverlay(layerParma1)
                }
            }
        },
        markertap(e) {
            let markerId = e.detail.markerId
            if (this.cateId == 0) {
                this.$asynApi.getSpotDetail(markerId).then(res => {
                    if (res.code == 200) {
                        this.markerInfo = res.data
                        this.showDetail = true

                        if (this.innerAudioContext) {
                            this.innerAudioContext.stop();
                            this.innerAudioContext = null
                            this.playStatus = false
                        }
                    }
                })
            } else {
                let result = this.markers.find(item => {
                    return item.id == markerId
                })
                this.markerInfo = result
                if (result.title.indexOf('游客中心') != -1) {
                    // console.log(result)
                    this.showDetail = true
                    if (this.innerAudioContext) {
                        this.innerAudioContext.stop();
                        this.innerAudioContext = null
                        this.playStatus = false
                    }
                } else {
                    this.go()
                }
            }
        },
        previewImage(url) {
            uni.previewImage({
                urls: [this.$baseUrl + url]
            })
        },
        navTo(url) {
            uni.navigateTo({
                url: url
            })
        },
        go() {
            console.log(this.markerInfo);
            if (this.markerInfo.latitude && this.markerInfo.longitude) {
                uni.openLocation({
                    latitude: Number(this.markerInfo.latitude),
                    longitude: Number(this.markerInfo.longitude),
                    name: this.markerInfo.spotName ? this.markerInfo.spotName : this.markerInfo.title
                })
            }
        },
        startMusic() {
            this.innerAudioContext = uni.createInnerAudioContext();
            this.innerAudioContext.autoplay = false
            this.innerAudioContext.src = this.$baseUrl + this.markerInfo.explainMusic;
            if (this.playStatus == false) {
                this.innerAudioContext.play()
                this.playStatus = true
            }
            this.innerAudioContext.onPlay(() => {
                this.playStatus = true
            });
            this.innerAudioContext.onError((res) => {
                console.log(res.errMsg);
                console.log(res.errCode);
            });
            this.innerAudioContext.onTimeUpdate(res => {
                this.playStatus = true
            })
        },
        pauseMusic() {
            this.innerAudioContext.pause()
            this.playStatus = false
        },
        closeDetail() {
            this.showDetail = false;
            this.markerInfo = null;
            if (this.innerAudioContext) {
                this.innerAudioContext.stop();
                this.innerAudioContext = null
                this.playStatus = false
            }
        },
        regionchange(e) {
            console.log(e)
            if (e.type == 'end') {
            	let currentLocation = e.detail.centerLocation
            	const result = IsPtInPoly(currentLocation.latitude, currentLocation.longitude, datas.areaPoints)
            	// console.log(result)
            	if (!result) {
            		this.mapContext.moveToLocation({
                latitude: 39.645243,
                longitude: 111.444696
            		})
            	}
            }
        }
    }
}
</script>

<style lang="less" scoped>
.flex {
    display: flex;
    align-items: center;
}

.mapBox {
    width: 100%;
    height: 100%;
    position: relative;
    .topBox {
        // background: url("../static/addFromTop.png");
        background-size: 100% 100%;
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 30rpx 50rpx 30rpx 50rpx;
        image {
            width: 150rpx;
            height: 150rpx;
            opacity: 0.8;
        }
        color: #fff;
        font-weight: 600;
        font-size: 40rpx;
        font-style: italic;
    }
}

#map {
    width: 100%;
    height: 100vh;
}

.marker-point {
    // position: relative;
    display: flex;
    align-items: center;
    text-align: center;

    .marker-img {
        // position: absolute;
        // left: 0;
        width: 35px;
        height: 40px;
    }

    .marker-name {
        // position: absolute;
        // left: 20px;
        // z-index: -1;
        padding: 4px 10px 4px 14px;
        white-space: nowrap;
        background-color: #fff;
        border-radius: 0 100px 100px 0;
        font-size: 14px;
        margin-left: -7px;
    }
}

.top {
    position: absolute;
    width: 100%;
    top: 0;
    left: 0;
    background: rgba(255, 255, 255, 0.6);
    box-sizing: border-box;
    padding: 20rpx;
    justify-content: space-between;

    .cateList {
        width: 100%;
        white-space: nowrap;

        .cate-item {
            display: inline-block;
            color: rgba(0, 0, 0, 0.85);
            font-size: 28rpx;
            // margin: 0 27rpx;
            height: 60rpx;
            line-height: 60rpx;
            padding: 0 30rpx;
        }

        .active {
            background: #07b9b9;
            color: #fff;
            border-radius: 8rpx;
        }
    }
}

.aside {
    position: fixed;
    right: 20rpx;
    bottom: 200rpx;

    image {
        width: 100rpx;
        height: 100rpx;
    }

    font-size: 28rpx;
    color: #fff;
}

.bottom {
    position: absolute;
    bottom: 0;
    left: 0;
    width: 100%;
    background: #fff;
    border-top-left-radius: 30rpx;
    border-top-right-radius: 30rpx;
    padding: 25rpx;

    .title {
        justify-content: space-between;
        width: 100%;
        margin-bottom: 20rpx;

        > view {
            color: #000000;
            font-size: 36rpx;
            font-weight: bold;
            position: relative;

            view {
                position: absolute;
                bottom: 0;
                left: 0;
                width: 100%;
                height: 13rpx;
                background: linear-gradient(
                    to right,
                    rgba(7, 185, 185, 0),
                    rgba(7, 185, 185, 1)
                );
            }
        }

        > text {
            font-size: 28rpx;
            color: #07b9b9;
        }
    }

    .imgBox {
        width: 100%;
        white-space: nowrap;
        margin-bottom: 20rpx;

        .img-item {
            display: inline-block;
            width: 200rpx;
            height: 200rpx;
            margin-right: 20rpx;

            image {
                width: 100%;
                height: 100%;
                border-radius: 8rpx;
            }
        }
    }

    .desc {
        line-height: 50rpx;
        font-size: 28rpx;
        width: 100%;
        max-height: 500rpx;
        overflow-y: scroll;
        color: #000000;
        margin-bottom: 20rpx;
    }

    .btn {
        width: 100%;
        background: #07b9b9;
        color: #fff;
        font-size: 28rpx;
        border-radius: 100rpx;
        height: 80rpx;
        line-height: 80rpx;
        text-align: center;
    }

    .audio-btn {
        position: absolute;
        width: 120rpx;
        height: 120rpx;
        right: 20rpx;
        bottom: 200rpx;

        image {
            width: 100%;
            height: 100%;
        }
    }
}
</style>